package com.code.leetcode.before50;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/7/22 10:16
 */
public class The41 {
    public int firstMissingPositive(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] > 0 && nums[i] < nums.length && nums[nums[i] - 1] != nums[i]) {
                swap(nums, i, nums[i] - 1);
            }
        }

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1)
                return  i + 1;
        }
        return nums.length + 1;
    }

    public void swap(int[] nums, int index1, int index2) {
        int x = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = x;
    }
}





/**
 * 原地 hash
 * @param nums
 * @return
 *      public int firstMissingPositive(int[] nums) {
 *         if (nums == null || nums.length < 1) return 0;
 *         HashSet<Integer> set = new HashSet<>();
 *         for (int num : nums) {
 *             set.add(num);
 *         }
 *
 *         for (int i = 1; i <= nums.length; i++) {
 *             if (!set.contains(i)) return i;
 *         }
 *         return nums.length + 1;
 *     }
 *
 */